package com.changfen.client.delayQueue;

import io.lettuce.core.*;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.Calendar;
import java.util.List;

/**
 * @author changfeng.chen@things-matrix.com
 * @date 2022/8/29 16:35
 **/
public class DelayQueue {

    public static void main(String[] args) {
        RedisURI redisUri = RedisURI.builder().withHost("localhost").withPort(6379).withPassword("thingsmatrix@8".toCharArray()).build();

        RedisClient redisClient = RedisClient.create(redisUri);
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisCommands<String, String> syncCommands = connection.sync();

        syncCommands.zadd("delay_queue", System.currentTimeMillis() + 10_000L, "delayQueue1");
        syncCommands.zadd("delay_queue", System.currentTimeMillis() + 20_000L, "delayQueue2");
        syncCommands.zadd("delay_queue", System.currentTimeMillis() + 30_000L, "delayQueue3");
        syncCommands.zadd("delay_queue", System.currentTimeMillis() + 40_000L, "delayQueue4");

        while (syncCommands.zcard("delay_queue") > 0) {
            List<String> delay_queue =
                    syncCommands.zrangebyscore("delay_queue", Range.create(0, System.currentTimeMillis()), Limit.create(0, -1));
            if (!CollectionUtils.isEmpty(delay_queue)) {
                syncCommands.zrem("delay_queue", delay_queue.get(0));
            }
        }
        connection.close();
        redisClient.shutdown();




    }


}
